import numpy as np
import torch
import matplotlib.pyplot as plt
import cv2
from segment_anything import sam_model_registry, SamAutomaticMaskGenerator, SamPredictor
from PIL import Image, ImageDraw, ImageFont
import os


def show_points(coords, labels, ax, marker_size=375):
    pos_points = coords[labels==1]
    neg_points = coords[labels==0]
    ax.scatter(pos_points[:, 0], pos_points[:, 1], color='green', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)
    ax.scatter(neg_points[:, 0], neg_points[:, 1], color='red', marker='*', s=marker_size, edgecolor='white', linewidth=1.25)   
    


def show_mask(mask, ax, random_color=False):
    if random_color:
        color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
    else:
        color = np.array([30/255, 144/255, 255/255, 0.6])
    h, w = mask.shape[-2:]
    mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
    ax.imshow(mask_image)



if __name__ == "__main__":
    image = cv2.imread('images/1.jpg')
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    #显示图片
    # plt.figure(figsize=(10,10))
    # plt.imshow(image)
    # plt.axis('on')
    # plt.show()
    
    sam_checkpoint = "./model/sam_vit_h_4b8939.pth"  #sam模型路径
    model_type = "vit_h"    #sam模型类别

    device = "cuda"     #使用GPU

    sam = sam_model_registry[model_type](checkpoint=sam_checkpoint)     #载入模型
    sam.to(device=device)

    predictor = SamPredictor(sam)   #定义预测器

    input_point = np.array([[550, 375]])
    input_label = np.array([1])         #手动设置标记点的位置与标签

    # plt.figure(figsize=(10,10))
    # plt.imshow(image)
    # show_points(input_point, input_label, plt.gca())
    # plt.axis('on')
    # plt.show()  

    predictor.set_image(image)          #设置将要进行预测的图片
    masks, scores, logits = predictor.predict(
        point_coords=input_point,
        point_labels=input_label,
        multimask_output=True,
    )

    print(masks.shape)

    for i, (mask, score) in enumerate(zip(masks, scores)):
        plt.figure(figsize=(10,10))
        plt.imshow(image)
        show_mask(mask, plt.gca())
        show_points(input_point, input_label, plt.gca())
        plt.title(f"Mask {i+1}, Score: {score:.3f}", fontsize=18)
        plt.axis('off')
        plt.show()  
    